using System;
using System.Configuration;
using System.Xml;
using System.Xml.Xsl;
using System.Web;


/*	-----------------------------------------------------------------------	
	Copyright:	umlungu consulting (Pty) ltd
	Author:		Alan Benington	
	Started:	2005-05-15	
	Status:		release	
	Version:	2.0.0
	Buidl:		20070616
	License:	GNU General Public License
	-----------------------------------------------------------------------	*/
	
/*	-----------------------------------------------------------------------	
	Development Notes:
	==================
	20070524:	Modification for .Net 2.0
	20070616:	Addition of config object
	-----------------------------------------------------------------------	*/
	
namespace umlungu.engineX.webX {
	/// <summary>
	/// umlungu engineX web framework, site class.
	/// </summary>
	public class siteX {
		#region Invisible properties (new)
		x_config config;
		#endregion

		#region Invisible properties
/*	original globals...
		private static bool wantdbgfile = false;
		private static bool wantprofiledbgfile = false;
		private static bool wantaccsummdbgfile = false;
		private static bool wantbilldetdbgfile = false;
		private static bool wantformdbgfile = false;
		private static bool wantchksubmit = false;
		private static bool wantsubmitastxt = true;	submit the data as a text output rather than email (wfrelay.asp)
		private static bool wantdataout = true;		dataoutput when wfcurrpgestr == 'last'
		private static bool wantxslout = false;		output transformed xml as an xsl template file
		private static bool wanthtmout = false;		default, can be changed by a command line parameter
		private static bool wantvalidxhtml = false;	if getting html, only accept valid xml 
*/
		private static string defaultsName = "x_site";
		
		private string sitename, homelink;
		private int loginattempts, timeoutform, timeoutserv;
		private System.Web.UI.Page page;
		private XmlDocument defaults;
		// properties intialised from App Settings (Web.config)
		private string sitePrefix, pathPrefix;
		// properties intialised from defaults file
		private bool wantlive, wantapp, wantdrop, wantsearch, wantbrowsers, wantalllinks, wantlogs;
		private bool ismovies, ismetatags;
		private string vermaj, vermin, siteid, name, emailsuffix, email, baseasp, editasp, copyright, type, preload, cellrelinfo, cellcontent;
		private string imagedir, contentdir, scriptsdir, stylesdir;
		private XmlNode movies, metatags;
		private XmlElement logs, sitexml;
		private bool debug = false;
		#endregion

		#region Constants
		#endregion

		#region Visible properties
		public int LoginAttempts	{ get { return loginattempts;}}
		public int TimeoutForm		{ get { return timeoutform;}}
		public int TimeoutServ		{ get { return timeoutserv;}}
		public bool IsMetatags		{ get { return ismetatags;}}
		public bool WantLive		{ get { return wantlive;}}
		public bool WantBrowsers	{ get { return wantbrowsers;}}
		public bool WantSearch		{ get { return wantsearch;}}
		public bool WantDrop		{ get { return wantdrop;}}
		public bool WantLogs		{ get { return wantlogs;}}
		public bool WantAllLinks	{ get { return wantalllinks;}}
		public bool SiteScript		{ get { return (((XmlElement) sitexml.SelectSingleNode("scripts")).GetAttribute("sitescript")=="yes")? true : false;}}
		
		public string HomeLink		{ get { return homelink;}}
		public string Base			{ get { return baseasp;}}
		public string Edit			{ get { return editasp;}}
		public string Name			{ get { return name;}}
		public string VerMaj		{ get { return vermaj;}}
		public string VerMin		{ get { return vermin;}}
		public string SiteID		{ get { return siteid;}}
		public string Preload		{ get { return preload;}}
		public string ImageDir		{ get { return imagedir;}}
		public string ContentDir	{ get { return contentdir;}}
		public string ScriptsDir	{ get { return scriptsdir;}}
		public string StylesDir		{ get { return stylesdir;}}
		
		public string LinksTemplate		{ get { return String.Concat(siteid, "_", "x_links_xml");}}
		public string FormsTemplate		{ get { return String.Concat(siteid, "_", "x_formobjs_xml");}}
		public string GlossTemplate		{ get { return String.Concat(siteid, "_", "x_gloss_xml");}}
		public string ProfileTemplate	{ get { return String.Concat(siteid, "_", "x_profile_xml");}}
		public string ContentTemplate	{ get { return String.Concat(siteid, "_", "x_content_xsl");}}
		
		public string SiteUrl	{ get { return(String.Concat("http://", sitePrefix, pathPrefix));}}
		public string Url		{ get { return(String.Concat("http://", sitePrefix, pathPrefix, siteid, "/"));}}
		public string SecureUrl	{ get { return(String.Concat("https://", sitePrefix, pathPrefix, siteid, "/"));}}
		
		public XmlElement SiteXml	{ get { return sitexml;}}
		public XmlElement Logs		{ get { return logs;}}
		public XmlDocument Xml		{ get { return defaults;}}
		public XmlNodeList Scripts	{ get { return sitexml.SelectNodes("scripts/script");}}
		#endregion

		#region Constructors/Destructors
		/// <summary>Constructor</summary>
		public siteX() {
			// this constructor is here to allow serialisation
		}
		public siteX(System.Web.UI.Page thispage, string thisname, bool wantdebug) {
			page = thispage;
			sitename = thisname;
			debug = wantdebug;
			initialise();
		}
		#endregion
		
		#region Public methods
		/// <summary>
		/// Method description
		/// </summary>
		public void KillSite() {
			openSite();
			sitexml = (XmlElement)defaults.DocumentElement.SelectSingleNode("//site");
			if (sitexml != null && !wantapp) {
				unloadTemplates();
				page.Application.Remove(sitename);
				}
		}
		/// <summary>
		/// Method description
		/// </summary>
		public bool WantSecureRedir() {
			return(wantlive? true : false);
		}
		/// <summary>
		/// Method description
		/// </summary>
		// This function gets the flash object (assume only one for now) and rteplaces any "s with 's so that this can be written to 
		public XmlNode GetFlash(string thismov) {
			return (sitexml.SelectSingleNode("movies/movie[@name='" + thismov + "']"));
		}
		/// <summary>
		/// Method description
		/// </summary>
		public string GetFlashAttr(string thisattr) {
			XmlNode thisfla = sitexml.SelectSingleNode(String.Concat("movies/flash/", thisattr));
			return (thisfla != null)? thisfla.InnerText : "";
		}
		/// <summary>
		/// Method description
		/// </summary>
		public string GetMovieAttr(string thisattr, string thisname) {
			XmlNode thisfla = sitexml.SelectSingleNode(String.Concat("movies/movie[@name='", thisname, "']/", thisattr));
			return (thisfla != null)? thisfla.InnerText : "";
		}
		/// <summary>
		/// Method description
		/// </summary>
		public string GetBodyAttribs() {
			// leftmargin='0' topmargin='0' marginwidth='0' marginheight='0'
			string bodystr = getBodyAttr("leftmargin");
			bodystr += getBodyAttr("topmargin");
			bodystr += getBodyAttr("marginwidth");
			bodystr += getBodyAttr("marginheight");
			return(bodystr);
		}
		/// <summary>
		/// Method description
		/// </summary>
		public void Save() {
			defaults.Save(page.Server.MapPath(String.Concat(defaultsName, "_dbg.xml")));
		}
		#endregion

		#region Protected methods
		/// <summary>
		/// Method description
		/// </summary>
		protected void _Debug(string label, params string[] outparam) {
			if (debug) {
				page.Response.Write("\n<!-- siteX.");
				page.Response.Write(label);
				page.Response.Write("::\n");
				for (int i=0; i < outparam.Length; i++)
					page.Response.Write(outparam[i]);
				page.Response.Write("\n");
				//Response.Write(getElapsed());
				page.Response.Write("-->\n");
			}
		}
		#endregion

		#region Private methods
		/// <summary>
		/// Initialise the object
		/// </summary>
		private void initialise() {
			config = new x_config();
			// initialise static default properties
			loginattempts = 3;
			homelink = "sitehome";
			timeoutform = 60;
			timeoutserv = 120;

			openSite();
			sitexml = (XmlElement)defaults.DocumentElement.SelectSingleNode("//site");
			
			// initialise default properties from default file
			if (sitexml != null) {
				siteid = sitexml.SelectSingleNode("siteid").InnerText;
				// site path related properties...
				wantlive = (sitexml.GetAttribute("live") == "yes") ? true : false;
				sitePrefix = config.Host;
				pathPrefix = config.Path;
				
				wantapp = (sitexml.GetAttribute("cache") == "yes") ? true : false;
				wantdrop = (sitexml.GetAttribute("dropmenus") == "yes") ? true : false;
				wantsearch = (sitexml.GetAttribute("search") == "yes") ? true : false;
				wantbrowsers = (sitexml.GetAttribute("browsers") == "yes") ? true : false;
				wantalllinks = (sitexml.GetAttribute("alllinks") == "yes") ? true : false;
				vermaj = sitexml.GetAttribute("ver_maj");
				vermin = sitexml.GetAttribute("ver_min");
				logs = (XmlElement) sitexml.SelectSingleNode("logs");
				wantlogs = (logs != null)? true : false;
				name = sitexml.SelectSingleNode("name").InnerText;
				emailsuffix = "@" + sitexml.SelectSingleNode("email_suffix").InnerText;
				email = sitexml.SelectSingleNode("email_prefix").InnerText + emailsuffix;
				baseasp = (sitexml.SelectSingleNode("baseasp") != null)? sitexml.SelectSingleNode("baseasp").InnerText : "default.aspx";
				editasp = (sitexml.SelectSingleNode("editasp") != null)? sitexml.SelectSingleNode("editasp").InnerText : "manage.aspx";
				copyright = sitexml.SelectSingleNode("copyright").InnerText;
				// get and initialise the layout properties
				type = sitexml.GetAttribute("type");
				cellrelinfo = getCellWidth("relinfo");
				cellcontent = getCellWidth("content");
				// get and initialise the xml/xsl references
				loadTemplates();
				// get directory settings
				getDirectories();
				// identify images to preload
				preload = loadImages();
				// check if movies are defined
				movies = sitexml.SelectSingleNode("movies");
				ismovies = (movies != null) ? true : false;
				// load the metatags
				metatags = sitexml.SelectSingleNode("metatags");
				ismetatags = (metatags != null) ? true : false;
				// get timeout settings
				getTimeout();
			}
		}
		/// <summary>
		/// Open xml default file and read values...
		/// </summary>
		private void openSite() {
			if (page.Application[sitename] == null) {
				defaults = new XmlDocument();
				defaults.Load(page.Server.MapPath(String.Concat(defaultsName, ".xml")));
				page.Application.Set(sitename, defaults);
			} else
				defaults = (XmlDocument) page.Application[sitename];
		}
		/// <summary>
		/// Method description
		/// </summary>
		private string getBodyAttr(string attr) {
			XmlNode thisnode = sitexml.SelectSingleNode(String.Concat("layout/body[@name='", attr, "']"));
			string thisstr = String.Concat(attr, "=");
			thisstr += (thisnode != null)? String.Concat("'", thisnode.InnerText, "' ") : "'0' ";
			return(thisstr);
		}
		/// <summary>
		/// Method description
		/// </summary>
		private string getCellWidth(string thiscell) {
			XmlNode thiswid = sitexml.SelectSingleNode("layout/cell[@name='" + thiscell + "']");
			return (thiswid == null)? "*" : thiswid.InnerText;
		}
		/// <summary>
		/// Method description
		/// </summary>
		private void loadTemplates() {
			_Debug("loadTemplates");
			XmlElement template, templselem = (XmlElement) sitexml.SelectSingleNode("templates");
			XmlNodeList templates = templselem.SelectNodes("template");
			string templname;
			foreach (XmlNode templ in templates) {
				template = (XmlElement) templ;
				templname = loadTemplate(templselem.GetAttribute("dir"), template.GetAttribute("name"),  (template.GetAttribute("xsl") == "yes"));
				template.SetAttribute("loaded", templname);
				}
		}
		/// <summary>
		/// Method description
		/// </summary>
		private string loadTemplate(string templdir, string templname, bool isxsl) {
			string ext = isxsl ? "xsl" : "xml";
			string tmplname = (templdir == "")? templname : String.Concat(templdir, "/", templname);
			string tmplFile = page.Server.MapPath(tmplname + "." + ext);
			tmplname = String.Concat(siteid, "_", templname, "_", ext);
			if (isxsl) {
				XslCompiledTransform xsltmpl = new XslCompiledTransform();
				xsltmpl.Load(tmplFile);
				page.Application.Set(tmplname, xsltmpl);
			} else {
				XmlDocument xmltmpl = new XmlDocument();
				xmltmpl.Load(tmplFile);
				page.Application.Set(tmplname, xmltmpl);
			}
			_Debug("loadTemplate", "name:", tmplname);
			return(tmplname);
		}
		/// <summary>
		/// Method description
		/// </summary>
		private void unloadTemplates() {
			XmlNodeList templates = sitexml.SelectNodes("templates/template");
			XmlElement template;
			string tmplname, tmplext;
			foreach (XmlNode templ in templates) {
				template = (XmlElement) templ;
				tmplname = template.GetAttribute("name");
				tmplext = (template.GetAttribute("xsl") == "yes") ? "xsl" : "xml";
				page.Application.Remove(tmplname + "_" + tmplext);
				}
		}
		/// <summary>
		/// Method description
		/// </summary>
		private string loadImages(){
			XmlNodeList images = sitexml.SelectNodes("images/image");
			XmlElement image;
			string loadstr = "";
			foreach (XmlNode img in images) {
				image = (XmlElement) img;
				if(image.GetAttribute("preload") == "yes") {
					if (loadstr != "")
						loadstr += ", ";
					loadstr += "'" + imagedir + "/" + image.InnerText + "'";
				}
			}
			return(loadstr);
		}
		/// <summary>
		/// Method description
		/// </summary>
		private void getTimeout() {
			XmlNode timenode = sitexml.SelectSingleNode("timeout");
			if (timenode != null) {
				XmlNode formnode = timenode.SelectSingleNode("formhandler");
				if (formnode != null)
					timeoutform = Convert.ToInt32(formnode.InnerText);
				XmlNode servnode = timenode.SelectSingleNode("servicehandler");
				if (servnode != null)
					timeoutserv = Convert.ToInt32(servnode.InnerText);
			}
		}
		/// <summary>
		/// Method description
		/// </summary>
		private void getDirectories() {
			imagedir = getDirectory("images");
			contentdir = getDirectory("content");
			scriptsdir = getDirectory("scripts");
			stylesdir = getDirectory("styles");
		}
		private string getDirectory(string dir) {
			XmlElement direlem = (XmlElement) sitexml.SelectSingleNode(dir);
			return ((direlem != null)? String.Concat(direlem.GetAttribute("dir"), "/") : "");
		}
		#endregion
	}
	
	/// <summary>
	/// umlungu engineX web framework, browser class.
	/// </summary>
	public class browserX
	{
		/// <summary>
		/// Local objects and properties
		/// </summary>
		private bool dom, ie, ie4, ie5, ie6, ns, ns4, ns6, ns7, mz5, op, op7;
		private static string ie4id = "compatible; MSIE 4.";
		private static string ie5id = "compatible; MSIE 5.";
		private static string ie6id = "compatible; MSIE 6.";
		private static string ns7id = "Netscape7";
		private static string ns6id = "Netscape6";
		private static string mz5id = "Mozilla/5.";
		private static string ns4id = "Mozilla/4.";
		private static string op7id = "Opera/7";
		private static string opid = "Opera";
		private string browser;
		public string Browser	{
			get	{	return browser;	}	
			set	{	browser = value;	}
		}
		
		/// <summary>
		/// Public properties
		/// </summary>
		public bool DOM	{ get {return dom;}}
		public bool IE	{ get {return ie;}}
		public bool IE4	{ get {return ie;}}
		public bool IE5	{ get {return ie;}}
		public bool IE6	{ get {return ie;}}
		public bool NS4	{ get {return ns4;}}
		public bool NS6	{ get {return ns6;}}
		public bool NS7	{ get {return ns7;}}
		public bool NS	{ get {return ns;}}
		public bool MZ5	{ get {return mz5;}}
		public bool OP	{ get {return op;}}
		public bool OP7	{ get {return op7;}}
		public bool IsStandard { get { return((ie6 || ns7 || mz5) && !op); } }
		public string FormString { get { return(""); } }
		public string BrowserString { get { return(dom ? "DOM" : ns4 ? "NS4" : "IE4"); } }
		public string BrowserCode {
			get {
				if (this.IE4)
					return("IE4");
				else if (this.IE5)
					return("IE5");
				else if (this.IE6)
					return("IE6");
				else if (this.NS6)
					return("NS6");
				else if (this.NS7)
					return("NS7");
				else if (this.NS4)
					return("NS4");
				else if (this.MZ5)
					return("MZ5");
				else if (this.OP7)
					return("OP7");
				else
					return("");
			}
		}
		
		#region Public methods
		/// <summary>Constructor</summary>
		public browserX(System.Web.UI.Page thispage) {
			browser = (string) thispage.Request.ServerVariables["HTTP_USER_AGENT"];
			initialise();
		}
		public browserX(string useragent) {
			browser = useragent;
			initialise();
		}
		#endregion

		#region Protected methods
		#endregion

		#region Private methods
		/// <summary>
		/// Initialise the properties
		/// </summary>
		private void initialise() {
			ie4 = ie5 = ns = ns4 = ns6 = ns7 = mz5 = op = op7 = false;
			dom = ie = ie6 = true;
			if (browser != "" && browser != null) {
				ie4 = (browser.IndexOf(ie4id) < 0)? false : true;
				ie5 = (browser.IndexOf(ie5id) < 0)? false : true;
				ie6 = (browser.IndexOf(ie6id) < 0)? false : true;
				ns7 = (browser.IndexOf(ns7id) < 0)? false : true;
				ns6 = (browser.IndexOf(ns6id) < 0)? false : true;
				ns4 = (browser.IndexOf(ns4id) < 0)? false : true;
				mz5 = (browser.IndexOf(mz5id) < 0)? false : true;
				op = (browser.IndexOf(opid) < 0)? false : true;
				op7 = (browser.IndexOf(op7id) < 0)? false : true;
				dom = (ie6 || ie5 || ns6 || ns7) ? true : false;
				ie = (ie6 || ie5 || ie4) ? true : false;
				ns = (ns4 || ns6 || ns7) ? true : false;
			}
		}
		#endregion
	}
}

